package com.example.weather2;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.xmlpull.v1.XmlPullParser;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;

public class MainActivity extends AppCompatActivity implements Runnable {

    HttpURLConnection httpConn = null;

    InputStream din = null;

    Vector<String> date = new Vector<String>();
    Vector<String> low = new Vector<String>();
    Vector<String> high = new Vector<String>();
    Vector<String> summaryDay = new Vector<String>();
    Vector<String> summaryNight = new Vector<String>();
    Vector<String> wind = new Vector<String>();

    Vector<Bitmap> bitmap = new Vector<Bitmap>();

    String city = "";
    LinearLayout body;
    Button select;
    EditText value;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("天气查询");

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.INTERNET)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.INTERNET}, 0);
        }

        body = (LinearLayout) findViewById(R.id.my_view);
        select = (Button) findViewById(R.id.select);
        value = (EditText) findViewById(R.id.values);

        value.setTextColor(Color.parseColor("#FFFFFF"));

        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                hideInput();

                body.removeAllViews();//移除当前的所有结果
                city = value.getText().toString();

                if (!city.trim().equals("")) {

                    Toast.makeText(MainActivity.this, "正在查询天气信息...", Toast.LENGTH_SHORT).show();
                    Thread th = new Thread(MainActivity.this);
                    th.start();

                } else {
                    Toast.makeText(MainActivity.this, "请输入城市名！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                }
        }
    }


    @Override
    public void run() {
        // TODO Auto-generated method stub
        date.removeAllElements();
        low.removeAllElements();
        high.removeAllElements();
        bitmap.removeAllElements();
        summaryDay.removeAllElements();
        summaryNight.removeAllElements();
        wind.removeAllElements();

        //获取数据
        parseData();

        //通知UI线程显示结果
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);

    }

    //隐藏键盘
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    //获取数据
    public void parseData() {
        //city变量表示城市名字
        String weatherUrl = "http://wthrcdn.etouch.cn/WeatherApi?city=" + city;

        try {
            URL url = new URL(weatherUrl);
            //建立天气预报查询连接
            httpConn = (HttpURLConnection) url.openConnection();
            //采用GET请求方法
            httpConn.setRequestMethod("GET");
            //打开数据输入流
            din = httpConn.getInputStream();
            InputStreamReader in = new InputStreamReader(din);
            // 为输出创建BufferedReader
            BufferedReader buffer = new BufferedReader(in);

            String inputLine = "";
            String resultData = "";
            //使用循环来读取获得的数据
            while ((inputLine = buffer.readLine()) != null) {
                //在每一行后面加上一个"\n"来换行
                resultData += inputLine + "\n";
            }

            Log.d(TAG, resultData);

            //获得XmlPullParser解析器
            XmlPullParser xmlParser = Xml.newPullParser();

            //获得解析到的事件类别，这里有开始文档，结束文档，开始标签，结束标签，文本等等事件。
            xmlParser.setInput(new StringReader(resultData));

            int evtType = xmlParser.getEventType();
            while (evtType != XmlPullParser.END_DOCUMENT)//一直循环，直到文档结束
            {

                String tag = xmlParser.getName();
                switch (evtType) {
                    case XmlPullParser.START_TAG:

                        if ("date".equals(tag)) {

                            date.addElement(xmlParser.nextText() + ":");

                        } else if ("type".equals(tag)) {

                            summaryDay.addElement(xmlParser.nextText());

                        } else if ("high".equals(tag)) {

                            high.addElement("最" + xmlParser.nextText());

                        } else if ("low".equals(tag)) {

                            low.addElement("最" + xmlParser.nextText());
                        } else if ("fengxiang".equals(tag)) {
                            wind.addElement("风向:" + xmlParser.nextText());
                        }

                        break;

                    case XmlPullParser.END_TAG:
                        if ("weather".equals(tag)) {
                            Log.d(TAG, "date:" + date);
                            Log.d(TAG, "high:" + high);
                            Log.d(TAG, "low:" + low);
                            Log.d(TAG, "day:" + summaryDay);
                            Log.d(TAG, "wind:" + wind);
                        }

                        //标签结束
                    default:
                        break;
                }
                //如果xml没有结束，则导航到下一个节点
                evtType = xmlParser.next();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //释放连接
            try {
                din.close();
                httpConn.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    //显示结果handler
    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    showData();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    //显示结果
    public void showData() {

        body.removeAllViews();//清除存储旧的查询结果的组件
        body.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.weight = 160;
        params.height = 120;

        for (int i = 0; i < date.size(); i++) {
            LinearLayout linerlayout = new LinearLayout(this);
            linerlayout.setOrientation(LinearLayout.HORIZONTAL);

            //日期
            TextView dateView = new TextView(this);
            dateView.setHeight(30);
            dateView.setLayoutParams(params);
            dateView.setText(date.elementAt(i));
            dateView.setTextSize(15);
            dateView.setTextColor(Color.parseColor("#FFFFFF"));
            linerlayout.addView(dateView);

            //天气情况
            TextView dayView = new TextView(this);
            dayView.setHeight(30);
            dayView.setLayoutParams(params);
            dayView.setText(summaryDay.elementAt(i));
            dayView.setTextSize(15);
            dayView.setTextColor(Color.parseColor("#FFFFFF"));
            linerlayout.addView(dayView);

            //最高气温
            TextView highView = new TextView(this);
            highView.setHeight(30);
            highView.setLayoutParams(params);
            highView.setText(high.elementAt(i));
            highView.setTextSize(15);
            highView.setTextColor(Color.parseColor("#FFFFFF"));
            linerlayout.addView(highView);

            //最低气温
            TextView lowView = new TextView(this);
            lowView.setHeight(30);
            lowView.setLayoutParams(params);
            lowView.setText(low.elementAt(i));
            lowView.setTextSize(15);
            lowView.setTextColor(Color.parseColor("#FFFFFF"));
            linerlayout.addView(lowView);

            //风向
            TextView windView = new TextView(this);
            windView.setHeight(30);
            windView.setLayoutParams(params);
            windView.setText(wind.elementAt(i));
            windView.setTextSize(15);
            windView.setTextColor(Color.parseColor("#FFFFFF"));
            linerlayout.addView(windView);

            body.addView(linerlayout);

        }
    }
}
